import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class FileOperations {
    public List<String> readFromFile(String sourcePath) throws IOException {
        List<String> listOfWords = new ArrayList<String>();
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(
                        new FileInputStream(new File(sourcePath)), "UTF-8"));

        String nextLine;
        StringParser sp = new StringParser();

        try {
            while ((nextLine = reader.readLine()) != null) {
                List<String> words = sp.parse(nextLine);
                for (String word : words) {
                    listOfWords.add(word);
                }
            }
        } finally {
            reader.close();
        }
        return listOfWords;
    }

    public void writeAnagramsToFile(List<Set<String>> anagramGroups, String destinationPath)
            throws IOException {
        PrintWriter out = new PrintWriter(new File(destinationPath), "UTF-8");

        try {
            for (Set<String> set : anagramGroups) {
                if (set != null && set.size() > 1) {
                    for (String word : set) {
                        out.print(word + " ");
                    }
                    out.println();
                }
            }
        } finally {
            out.close();
        }
    }
}
